package com.gree.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.gree.commom.result.BaseResult;
import com.gree.manager.entity.Goods;
import com.gree.manager.mapper.GoodsMapper;
import com.gree.manager.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

/**
 * 商品服务实现类
 *
 * @author zhoubin
 * @since 1.0.0
 */
@Service
public class GoodsServiceImpl implements GoodsService {

	@Autowired
	private GoodsMapper goodsMapper;

	/**
	 * 商品新增-保存
	 *
	 * @param goods
	 * @return
	 */
	@Override
	public BaseResult saveGoods(Goods goods) {
		BaseResult baseResult = BaseResult.error();
		//如果goodsId不为空直接返回错误
		if (goods.getGoodsId()!=null){
			return baseResult;
		}
		//如果有详情，先转义
		if (!StringUtils.isEmpty(goods.getGoodsContent())){
			goods.setGoodsContent(HtmlUtils.htmlEscape(goods.getGoodsContent(), "UTF8"));
		}
		int result = goodsMapper.insert(goods);
		if (result>0){
			baseResult = BaseResult.success();
			baseResult.setMessage(String.valueOf(goods.getGoodsId()));
		}
		return baseResult;
	}

	/**
	 * 商品列表-分页查询
	 * @param goods
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
    @Override
    public BaseResult selectGoodsListByPage(Goods goods, Integer pageNum, Integer pageSize) {
		Page<Goods> page = new Page<>(pageNum,pageSize);
		QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
		//分类参数
		if (goods.getCatId()!=null&&goods.getCatId()!=0){
			queryWrapper.eq("cat_id",goods.getCatId());
		}
		//品牌参数
		if (goods.getBrandId()!=null&&goods.getBrandId()!=0){
			queryWrapper.eq("brand_id",goods.getBrandId());
		}
		//关键词
		if (!StringUtils.isEmpty(goods.getGoodsName())){
			queryWrapper.likeRight("keywords",goods.getGoodsName());
		}
		Page<Goods> goodsPage = goodsMapper.selectPage(page, queryWrapper);
		List<Goods> goodsList = goodsPage.getRecords();
		PageInfo<Goods> goodsPageInfo = new PageInfo<>(goodsList);
		return goodsList != null? BaseResult.success(goodsPageInfo):BaseResult.error();
    }

	/**
	 * 获取所有商品信息
	 * @return
	 */
	@Override
    public List<Goods> getAllGoodsInfo() {
		List<Goods> goods = goodsMapper.getAllGoodsInfo();
		return goods;
	}
}